<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Controller;

use Doctrine\ORM\EntityManager;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use Shop\Form\AddCartForm;
use User\Entity\Cart;
use User\Service\CartManager;

class CartController extends AbstractActionController
{
    private $translator;
    private $entityManager;
    private $cartManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager,
        CartManager     $cartManager
    )
    {
        $this->translator   = $translator;
        $this->entityManager= $entityManager;
        $this->cartManager  = $cartManager;
    }

    /**
     * 购物车首页
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('购物车'));
        $this->layout()->setVariable('currentPage', 'cartIndex');

        $array = [];

        if($this->shopPlugin()->checkUserLoginStatus()) {
            $userId         = $this->shopPlugin()->getUserLoginData('user_id');
            $cartGoodsList  = $this->entityManager->getRepository(Cart::class)->shopCartGoodsList($userId);
            $response       = $this->getEventManager()->trigger('shop.cart.index.show', $this, ['cartGoodsList' => $cartGoodsList, 'userId' => $userId, 'user_group_id' => $this->shopPlugin()->getUserLoginData('user_group_id')]);
            $array          = $response->last();
        } else $array['cartGoodsList'] = null;

        $array['cartIndexPartial'] = $this->shopPlugin()->shopPartial('cart');

        return $array;
    }

    /**
     * 直接购买添加
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addBuyNowAction()
    {
        return $this->addCart(true);
    }

    /**
     * 添加购物车
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        return $this->addCart();
    }

    /**
     * 全部变更是否选中
     * @return JsonModel
     */
    public function changeAllCartGoodsSelectedAction()
    {
        //判断是否登录
        if(!$this->shopPlugin()->checkUserLoginStatus()) return new JsonModel(['status' => 'false', 'loginStatus' => 'false', 'message' => $this->translator->translate('请登录后，再进行购物车添加!')]);

        $checkState = $this->params()->fromPost('checkState', '');
        $userId     = $this->shopPlugin()->getUserLoginData('user_id');
        $goodsChecked = $checkState == 'true' ? 1 : 2;
        $this->cartManager->updateCartGoods(['goodsChecked' => $goodsChecked], 0, $userId);

        return new JsonModel(['status' => 'true']);
    }

    /**
     * 变更选中
     * @return JsonModel
     */
    public function changeCartGoodsSelectedAction()
    {
        //判断是否登录
        if(!$this->shopPlugin()->checkUserLoginStatus()) return new JsonModel(['status' => 'false', 'loginStatus' => 'false', 'message' => $this->translator->translate('请登录后，再进行购物车添加!')]);

        $cartId = (int) $this->params()->fromPost('cartId', 0);
        $userId = $this->shopPlugin()->getUserLoginData('user_id');

        $cartGoods = $this->entityManager->getRepository(Cart::class)->findOneBy(['cartId' => $cartId, 'userId' => $userId]);
        if($cartGoods == null) return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('购物车内没有该商品!')]);

        $goodsChecked = $cartGoods->getGoodsChecked() == 1 ? 2 : 1;
        $this->cartManager->updateCartGoods(['goodsChecked' => $goodsChecked], $cartId, $userId);

        return new JsonModel(['status' => 'true']);
    }

    /**
     * 修改购物车商品数量
     * @return JsonModel
     */
    public function editCartGoodsNumAction()
    {
        //判断是否登录
        if(!$this->shopPlugin()->checkUserLoginStatus()) return new JsonModel(['status' => 'false', 'loginStatus' => 'false', 'message' => $this->translator->translate('请登录后，再进行购物车添加!')]);

        $cartId = (int) $this->params()->fromPost('cartId', 0);
        $buyNum = (int) $this->params()->fromPost('buyNum', 0);
        $userId = $this->shopPlugin()->getUserLoginData('user_id');

        if($buyNum <= 0) return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('商品购买数量不能为0!')]);

        $cartGoodsInfo = $this->entityManager->getRepository(Cart::class)->shopCartGoodsInfo($cartId, $userId);
        if($cartGoodsInfo == null) return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('该商品在购物车中不存在!')]);

        //修改购物车商品购买数量的触发事件
        $response = $this->getEventManager()->trigger('shop.cart.editBuyNum.pre', $this, ['buyNum' => $buyNum, 'userId' => $userId, 'cartGoods' => $cartGoodsInfo]);
        if($response->stopped()) {
            return new JsonModel($response->last());
        }
        $data = $response->last();
        $this->cartManager->updateCartGoods($data, $cartId, $userId);

        return new JsonModel(['status' => 'true']);
    }

    /**
     * 删除购物车中的商品
     * @return JsonModel
     */
    public function deleteCartGoodsAction()
    {
        //判断是否登录
        if(!$this->shopPlugin()->checkUserLoginStatus()) return new JsonModel(['status' => 'false', 'loginStatus' => 'false', 'message' => $this->translator->translate('请登录后，在进行此操作!')]);

        $cartId = $this->params()->fromRoute('id', -1);

        $cartGoods = $this->entityManager->getRepository(Cart::class)->findOneBy(['cartId' => $cartId, 'userId' => $this->shopPlugin()->getUserLoginData('user_id')]);
        if($cartGoods == null) return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('您的购物车中并无此商品!')]);

        $goodsId = $cartGoods->getGoodsId();
        if($this->cartManager->deleteCart([$cartId], $cartGoods->getUserId())) {
            $this->getEventManager()->trigger('shop.cart.deleteGoods.post', $this, ['userId' => $this->shopPlugin()->getUserLoginData('user_id'), 'goodsId' => $goodsId]);
            return new JsonModel(['status' => 'true']);
        }

        return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('购物车商品删除失败!')]);
    }

    /**
     * 清空购物车
     * @return JsonModel
     */
    public function clearCartGoodsAction()
    {
        //判断是否登录
        if(!$this->shopPlugin()->checkUserLoginStatus()) return new JsonModel(['status' => 'false', 'loginStatus' => 'false', 'message' => $this->translator->translate('请登录后，在进行此操作!')]);

        $cartGoods = $this->entityManager->getRepository(Cart::class)->findOneBy(['userId' => $this->shopPlugin()->getUserLoginData('user_id')]);
        if($cartGoods == null) return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('您的购物车中并无商品!')]);

        if($this->cartManager->clearCart($this->shopPlugin()->getUserLoginData('user_id'))) return new JsonModel(['status' => 'true']);

        return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('购物车清空删除失败!')]);
    }

    /**
     * 购物车添加
     * @param bool $buyNowStatus
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    private function addCart($buyNowStatus = false)
    {
        //判断是否登录
        if(!$this->shopPlugin()->checkUserLoginStatus()) return new JsonModel(['status' => 'false', 'loginStatus' => 'false', 'message' => $this->translator->translate('请登录后，再进行购物车添加!')]);

        $cartForm = new AddCartForm();
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $cartForm->setData($data);
            if($cartForm->isValid()) {
                $data = $cartForm->getData();
                //添加购物车前的事件处理
                $response = $this->getEventManager()->trigger('shop.cart.add.pre', $this, ['goodsData' => $data, 'buyNowStatus' => $buyNowStatus, 'userId' => $this->shopPlugin()->getUserLoginData('user_id')]);
                if($response->stopped()) {
                    return new JsonModel($response->last());
                }
                $data = $response->last();

                if($buyNowStatus) $data['buyNow'] = 1;//直接购买
                else $data['buyNow'] = 0;//非直接购买
                $buyNowGoods = $this->entityManager->getRepository(Cart::class)->findOneBy(['userId' => $this->shopPlugin()->getUserLoginData('user_id'), 'buyNow' => 1]);
                if($buyNowGoods) $this->cartManager->clearCart($buyNowGoods->getUserId(), true);

                $data['userId'] = $this->shopPlugin()->getUserLoginData('user_id');
                $cart = $this->cartManager->addCart($data);
                if($cart) {
                    $nextResponse = $this->getEventManager()->trigger('shop.cart.add.post', $this, ['goodsData' => $data, 'cart' => $cart, 'buyNowStatus' => $buyNowStatus, 'userId' => $this->shopPlugin()->getUserLoginData('user_id')]);
                    if ($nextResponse->stopped()) return new JsonModel($nextResponse->last());

                    return new JsonModel(['status' => 'true', 'message' => $this->translator->translate('购物车添加成功!')]);
                }
            }
        }

        return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('购物车添加失败!')]);
    }
}